/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package control;

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import componentes.BeanConector;
import componentes.BeanUsuario;
import componentes.BeanGestionUsuario;

/**
 *
 * @author Ximena del Pilar
 */
public class ServletUsuario
        extends HttpServlet {

    static final private String CONTENT_TYPE = "text/html";
    BeanConector bc;
    BeanGestionUsuario gestionUsuario;
    //Initialize global variables

    public void init() throws ServletException {
    }

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws
            ServletException, IOException {
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response) throws
            ServletException, IOException {
        conectarBD();
        gestionUsuario = new BeanGestionUsuario(bc);
        response.setContentType(CONTENT_TYPE);
        String login, pwd;
        if (request.getParameter("Validar Usuario") != null) {
            login = request.getParameter("login");
            pwd = request.getParameter("password");
            BeanUsuario usuario = this.gestionUsuario.ValidarUsuario(login, pwd);
            if (usuario != null) {
                if (usuario.getTipo().equals("administrador")) {
                    HttpSession sesion = request.getSession();
                    sesion.setAttribute("usuario", usuario);
                    gotoPage("Administrador.jsp", request, response);
                    desconectarBD();
                } else if (usuario.getTipo().equals("usuario")) {
                    BeanUsuario[] ArregloUsuarios;
                    ArregloUsuarios = this.gestionUsuario.ListarUsuarios();
                    request.setAttribute("ArregloUsuarios", ArregloUsuarios);
                    gotoPage("Usuario.jsp", request, response);
                    desconectarBD();
                }
            } else {
                gotoPage("Error.jsp", request, response);
            }
        }
    }

    private void gotoPage(String address, HttpServletRequest request,
            HttpServletResponse response) throws ServletException,
            IOException {
        RequestDispatcher dispatcher = request.getRequestDispatcher(address);
        dispatcher.forward(request, response);
    }

    public void destroy() {
        this.desconectarBD();
    }

    private void conectarBD() {
        this.bc = new BeanConector();
        bc.setDriver("com.mysql.jdbc.Driver");
        bc.setLogin("root");
        bc.setPassword("root");
        bc.setUrl("jdbc:mysql://localhost/usuariosdb");
        if (bc.conectar() == 1) {
            System.out.println("Conexion en la BD exitosa");
        } else {
            System.out.println("Error en la conexion a la BD");
        }
    }

    private void desconectarBD() {
        bc.cerrarCx();
    }
}
